//https://leetcode.cn/problems/recover-binary-search-tree/description/
class Solution {
public:
    TreeNode* err1 = nullptr;
    TreeNode* err2 = nullptr;
    int flag = 0;
    TreeNode* prev = nullptr;
    void InOrder(TreeNode* root)
    {
        if(!root) return;
        InOrder(root->left);
        if(prev != nullptr && prev->val > root->val)
        {
            flag++;
            if(flag == 1)
            {
                err1 = prev;
                err2 = root;
            }
            else 
            {
                err2 = root;
            }
        }
        prev = root;
        InOrder(root->right);
    }
    void recoverTree(TreeNode* root) {
        InOrder(root);
        if(err1 && err2) swap(err1->val,err2->val);
    }
};


//https://leetcode.cn/problems/successor-lcci/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        stack<TreeNode*> st;
        TreeNode*　cur = root;
        while(cur || !st.empty())
        {
            while(cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            st.pop();
            if(top->val > p->val)
                return top;
            
            cur = top->right;
        }
        return nullptr;
    }
};


class Solution {
public:
    //求二叉树的高度
    int TreeHeight(TreeNode* root)
    {
        if(!root) return 0;
        return 1 + max(TreeHeight(root->left),TreeHeight(root->right));
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        int leftTreeHeight = TreeHeight(root->left);
        int rightTreeHeight = TreeHeight(root->right);
        //左树和右树的高度不超过1 && 左树和右树都是平衡二叉树
        return abs(leftTreeHeight - rightTreeHeight) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};

//https://leetcode.cn/problems/successor-lcci/
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return root;
        swap(root->left,root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};
